package com.bjh.netty.client;

import com.bjh.netty.message.RpcMessage;
import com.bjh.req.Request;
import com.bjh.resp.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class RpcClientHandler extends SimpleChannelInboundHandler<RpcMessage> {

    ObjectMapper objectMapper = new ObjectMapper();


    private Response response;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        RpcMessage rpcMessage = new RpcMessage();
//        Request request = new Request();
//        request.setId("123");
//        String valueAsString = objectMapper.writeValueAsString(request);
//        rpcMessage.setObj(valueAsString);
//        rpcMessage.setDataLength(valueAsString.getBytes(Charset.forName("utf-8")).length);
//
//        ctx.writeAndFlush(rpcMessage);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcMessage rpcMessage) throws Exception {
        Object obj = rpcMessage.getObj();
        try{
            Response responseMessage = objectMapper.readValue(obj.toString(), Response.class);
            response = new Response();
            response.setErrInfo(responseMessage.getErrInfo());
            response.setIsOk(responseMessage.getIsOk());
            response.setData(responseMessage.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        ctx.close();
    }

    public Response getResponse() {
        return response;
    }

    public void setResponse(Response response) {
        this.response = response;
    }
}
